# encoding: utf-8
import os, sys, socket
from .log import LOGGER
import requests
# def init(rootdir, dirname):
#     # 创建临时目录
#     isExists = os.path.exists(os.path.join(rootdir, dirname))
#     if not isExists:
#         os.makedirs(dirname)


# 导入数据库驱动
import sqlite3


# 连接到数据库
# 数据库文件是“test.db”
# 如果数据库不存在的话，将会自动创建一个 数据库


def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d


"""
创建任务表
"""
task_listsql = """
create table task
(
    id          integer       not null primary key autoincrement,
    task_name   varchar(128)  not null unique,
    taskid      int           not null default 0,
    workdir     varchar(256)  not null default '',
    pre_ommand  varchar(1024) not null default '',
    post_ommand varchar(1024) not null default '',
    timeout int   not null default 10
);
"""


def initdb(filepath):
    """
    创建新sqlitedb, 存在则删除
    """
    try:
        dbfilepath = os.path.join(os.path.abspath(filepath), '.taskdb.sqlite')
        if os.path.exists(dbfilepath):
            os.remove(dbfilepath)
        conn = sqlite3.connect(dbfilepath)
        conn.row_factory = dict_factory
        cursor = conn.cursor()
        cursor.execute(task_listsql)
        conn.commit()

        cursor.close()
        conn.close()
    except Exception as e:
        LOGGER.error(e)
        LOGGER.error("初始化数据库失败")
        os._exit(127)


# 上传agent给服务器
def upload_agnet_info(configdata: dict):
    hostname = socket.gethostname()
    version = configdata.get("version", None)
    agentaddr = configdata.get("agentaddr", None)

    serveraddr = configdata.get("serveraddr", None)
    serverport = configdata.get("serverport", None)

    url = f"http://{serveraddr}:{serverport}"
    postdata = {
        "hostname": hostname,
        "version": version,
        "agentaddr": agentaddr,
    }

    try:
        requests.post(url=url, data=postdata)
    except Exception as e:
        LOGGER.error(f"上传agent信息失败 {e}")
